package com.example.asus.practice;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CAMERA extends AppCompatActivity {
//    private Camera camera;//定义一个摄像头对象
    Camera camera;
    private boolean isPreview = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        if(!android.os.Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this, "请安装SD卡", Toast.LENGTH_SHORT).show();
        }

        /**打开摄像头并预览*/

        final SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView);//用于显示摄像头预览
        final SurfaceHolder surfaceHolder = surfaceView.getHolder();//获取SurfaceHolder
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//设置SurfaceView自己不维护缓冲
        ImageButton preview = (ImageButton)findViewById(R.id.preview);
        preview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(isPreview){
                    camera=Camera.open(0);//打开摄像头预览
                    isPreview = true;
                }
                try {
                    camera.setPreviewDisplay(surfaceHolder);//设置用于显示预览的SurfaceView
                    Camera.Parameters parameters = camera.getParameters();//获取摄像头参数
                    parameters.setPictureFormat(PixelFormat.JPEG);//设置图片为JPG格式
                    parameters.set("图片质量：",80);//设置图片质量
                    camera.setParameters(parameters);//重新设置摄像头参数
                    camera.startPreview();//开始预览
                    camera.autoFocus(null);//设置自动聚焦
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        ImageButton takePicture = (ImageButton)findViewById(R.id.takephoto);
        takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //实现拍照功能
                if(camera != null){
                    camera.takePicture(null,null,jpeg);//进行拍照
                }
            }
        });
    }
    final Camera.PictureCallback jpeg = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);//根据拍照所得数据创建位图
            camera.stopPreview();//停止预览
            isPreview = false;//设置为非预览状态
            //获取SD卡中相片位置
            File appDir = new File(Environment.getExternalStorageDirectory(),"/DCIM/Camera/");
            if(!appDir.exists()){
                appDir.mkdir();
            }
            String fileName = System.currentTimeMillis() + ".jpg";//获取当前时间设置为文件名
            File file = new File(appDir,fileName);

            try{
                FileOutputStream fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);//将图片内容压缩为JPEG格式输出
                fos.flush();
                fos.close();
            }catch(FileNotFoundException e){
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                MediaStore.Images.Media.insertImage(CAMERA.this.getContentResolver(),file.getAbsolutePath(),fileName,null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            CAMERA.this.sendBroadcast((new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+""))));
            Toast.makeText(CAMERA.this, "照片保存至："+file, Toast.LENGTH_SHORT).show();
            resetCamera();//重新预览

        }
    };
    private void resetCamera(){
        if(!isPreview){
            camera.startPreview();//开启预览
            isPreview = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        /**停止预览并释放摄像头资源*/
        if(camera != null){
            camera.stopPreview();
            camera.release();
        }
    }
}
